﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;

namespace General.Mvc.Filters
{
    public class ResponseTimeFilterAttribute : ActionFilterAttribute
    {
        private const string ResponseTimeKey = "ResponseTimeKey";
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            // Start the timer   
            context.HttpContext.Items[ResponseTimeKey] = Stopwatch.StartNew();
        }
        public override void OnActionExecuted(ActionExecutedContext context)
        {
            Stopwatch stopwatch = (Stopwatch)context.HttpContext.Items[ResponseTimeKey];
            // Calculate the time elapsed   
            var timeElapsed = stopwatch.Elapsed;
            ContentResult result = new ContentResult();
            result.Content = "web service started, process time :" + timeElapsed.ToString();
            context.Result = result;
        }
    }
}
